from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

from com.sensemore.core.models import (
    UserRegisterReq, 
    UserRegisterRsp, 
    LoginReq, 
    UserInfoRsp
)
from com.sensemore.utils.db import Database
import logging
# 配置日志
logger = logging.getLogger(__name__)

router = APIRouter()
security = HTTPBearer()
db = Database()

@router.get("/")
async def root():
    return {"message": "Welcome to Sensemore API"}

@router.get("/protected-route")
async def protected_route(credentials: HTTPAuthorizationCredentials = Depends(security)):
    token = credentials.credentials
    logging.info(f"Received token: {token}")
    user_id = db.verify_token(token)
    if not user_id:
        raise HTTPException(status_code=401, detail="Invalid token")
    logging.info(f"Token verified successfully: {user_id}")
    return {"message": "You have access to protected route"}

@router.post("/user/register", response_model=UserRegisterRsp)
async def user_register(user_req: UserRegisterReq):
    try:
        # 注册新用户
        user_id, message = db.create_user(
            username=user_req.username,
            email=user_req.email,
            password=user_req.password
        )
        
        return UserRegisterRsp(
            user_id=user_id,
            username=user_req.username,
            email=user_req.email,
            message=message
        )
    except ValueError as e:
        logger.warning(f"Registration failed for {user_req.username}: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Registration error: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail="Internal server error")

@router.post("/user/login", response_model=UserInfoRsp)
async def user_login(login_req: LoginReq):
    try:
        # 验证用户登录
        result = db.verify_user(
            username=login_req.username,
            password=login_req.password
        )
        
        if not result:
            raise HTTPException(status_code=401, detail="Invalid credentials")
            
        user_id, email, token = result
        logger.info(f"User logged in successfully: {login_req.username} (ID: {user_id})")

        return UserInfoRsp(
            user_id=user_id,
            username=login_req.username,
            email=email,
            token=token
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Login error: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail="Internal server error")
